import { defineComponent, ref } from "vue";
import { formGroupProps } from "./types";
import Form from "../Form";
import CardView from "../CardView";
import { IFormRef, IFormSubmitCallBack } from "../Form/types";
import { formDataControl } from "@/command/apiTool";
export default defineComponent({
  name: "",
  props: formGroupProps,
  setup(_, { expose }) {
    const formsRef = ref<IFormRef[]>([]);

    const submit = (callBack: IFormSubmitCallBack) => {
      let allError = {};
      let allResult = {};
      return new Promise(async (resolve) => {
        for (let index = 0; index < formsRef.value.length; index++) {
          const element = formsRef.value[index];
          const { error, result } = await element.submit(undefined, true);
          allResult = { ...allResult, ...result };
          allError = { ...allError, ...error };
        }
        if (callBack) {
          callBack(formDataControl({ result: allResult, error: allError }));
        } else {
          resolve(formDataControl({ result: allResult, error: allError }));
        }
      });
    };

    expose({
      submit,
    });
    return () => {
      return (
        <div class="flex flex-col form-group  m-child-top-20">
          {_.data.map((e, i) => {
            return (
              <CardView class="flex flex-col " title={e.title}>
                <Form
                  data={e.data}
                  modelValue={_.modelValue}
                  onUpdate:modelValue={(data) => {
                    Object.keys(data).forEach((key) => {
                      _.modelValue[key] = data[key];
                    });
                  }}
                  ref={(r) => (formsRef.value[i] = r as never)}
                />
              </CardView>
            );
          })}
        </div>
      );
    };
  },
});
